package org.ligson.login;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.ligson.login.vo.AppFunction;
import org.ligson.login.vo.PA;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/***
 * curl 'http://10.170.200.171/crux-auth/login' \
 *   -H 'Content-Type: application/x-www-form-urlencoded' \
 *   --data-raw 'username=310000000999999999&password=90&CApsd=&fiscalYear=2021&mofDiv=319900000' \
 *   --compressed \
 *   --insecure
 *
 *
 *
 *   PHPSESSID=MDQxOWQxNjEtNzUyOS00ODM4LWExMTctNTFmODczYWQzODZk
 *
 *   curl -c 2.txt -IL 'http://10.170.200.171/' \
 *   -H 'Cookie: PHPSESSID=MDQxOWQxNjEtNzUyOS00ODM4LWExMTctNTFmODczYWQzODZk'
 *
 *
 *
 *   curl  -IL 'http://10.170.200.171/crux-uc/api/user/me' \
 *   -H 'Cookie: CRUXSESSIONID1=N2NkN2ZmMTItOWNmYi00YTRjLTlmYWMtMjVkYjJmMjQ0YmU4'
 *
 *   CRUXSESSIONID1	N2NkN2ZmMTItOWNmYi00YTRjLTlmYWMtMjVkYjJmMjQ0YmU4
 */
@Slf4j
public class LoginDemo2 {
    static BasicCookieStore cookieStore = new BasicCookieStore();
    //DefaultRedirectStrategy strategy = new DefaultRedirectStrategy();

    static CloseableHttpClient client = HttpClientBuilder.create()
            //.setRedirectStrategy(redirectStrategy)
            //.setRedirectStrategy(redirectStrategy)
            .setDefaultCookieStore(cookieStore).build();

    static String baseUrl = "https://jxtest.yonyougov.top";
    static String username = "999999999";
    static String password = "666";

    static ObjectMapper mapper = new ObjectMapper();

    static boolean login() throws Exception {
        List<NameValuePair> loginFormPairs = new ArrayList<>();
        //username=310000000999999999&password=90&CApsd=&fiscalYear=2021&mofDiv=319900000
        loginFormPairs.add(new BasicNameValuePair("username", username));
        loginFormPairs.add(new BasicNameValuePair("password", password));

        UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(loginFormPairs);

        HttpPost loginPost = new HttpPost(baseUrl + "/crux-auth/login");
        loginPost.setEntity(encodedFormEntity);
        CloseableHttpResponse res1 = client.execute(loginPost);
        System.out.println("{1}>>>>>>>>>>" + cookieStore.getCookies());

        HttpGet loginGet1 = new HttpGet(baseUrl + "/");
        CloseableHttpResponse res2 = client.execute(loginGet1);

        System.out.println("{2}>>>>>>>>>>" + cookieStore.getCookies());

        HttpGet meGet = new HttpGet(baseUrl + "/crux-uc/api/user/me");
        CloseableHttpResponse res3 = client.execute(meGet);

        System.out.println(EntityUtils.toString(res3.getEntity()));
        System.out.println("{3}>>>>>>>>>>" + cookieStore.getCookies());
        return true;
    }

    private static List<AppFunction> getAppFunctionByAppModule(String appModuleId) throws Exception {
        HttpGet loginGet1 = new HttpGet(baseUrl + "/crux-appmodule/api/appfunction?size=999999999&appModule.id=" + appModuleId);
        CloseableHttpResponse res2 = client.execute(loginGet1);

        return mapper.readValue(res2.getEntity().getContent(), new TypeReference<ArrayList<AppFunction>>() {
        });
    }

    private static List<String> getRolesByAppFunction(String appFunctionId) throws Exception {
        HttpGet loginGet1 = new HttpGet(baseUrl + "/crux-permission/api/functiongroup/function?functionId=" + appFunctionId);
        CloseableHttpResponse res2 = client.execute(loginGet1);
        String json = EntityUtils.toString(res2.getEntity());

        return mapper.readValue(json, new TypeReference<ArrayList<String>>() {
        });
    }

    private static List<PA> getPasByRoleId(String roleId) throws Exception {
        HttpGet loginGet1 = new HttpGet(baseUrl + "/crux-permission/api/permissionassignment?subjectType=FUNCTION_GROUP&subjectId=" + roleId + "&fetchProperties=id,subjectId,resourceId,type[id,code,name]");
        CloseableHttpResponse res2 = client.execute(loginGet1);
        String json = EntityUtils.toString(res2.getEntity());

        ArrayList<PA> functions = mapper.readValue(json, new TypeReference<ArrayList<PA>>() {
        });
        return functions;
    }

    public static void main(String[] args) throws Exception {
        mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        login();
        List<AppFunction> functions = getAppFunctionByAppModule("7");
        Set<String> roleIds = new HashSet<>();
        for (AppFunction function : functions) {
            log.debug("查找功能：{}对应的角色", function);
            List<String> roles = getRolesByAppFunction(function.getId());
            roleIds.addAll(roles);
        }

        System.out.println(roleIds);

        List<PA> pas = new ArrayList<>();
        for (String roleId : roleIds) {
            List<PA> paIds = getPasByRoleId(roleId);
            paIds.addAll(pas);
        }

        String json = mapper.writeValueAsString(pas);


    }
}
